package com.advertisementsystem.Servie.Impl;

import com.advertisementsystem.Dto.*;
import com.advertisementsystem.Mapper.AdScheduleMapper;
import com.advertisementsystem.Mapper.AdvertisementMapper;
import com.advertisementsystem.Servie.AdStatisticsService;
import com.advertisementsystem.vo.StatisticsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class AdStatisticsServiceImpl implements AdStatisticsService {

    @Autowired
    private AdScheduleMapper adScheduleMapper;
    @Autowired
    private AdvertisementMapper advertisementMapper;

    @Override
    public StatisticsVO getStatistics(Long advertiserId, Date startTime, Date endTime) {
        StatisticsVO vo = new StatisticsVO();

        log.info("查询统计数据: advertiserId={}, startTime={}, endTime={}",
                advertiserId, startTime, endTime);
        MetricsDTO metrics = getMetrics(advertiserId, startTime, endTime);
        log.info("基础指标: {}", metrics);
        vo.setMetrics(metrics);
        // 获取趋势数据
        vo.setTrend(getTrendData(advertiserId, startTime, endTime));

        // 获取TOP10广告
        vo.setTopAds(getTopAds(advertiserId, startTime, endTime));

        // 获取点击率分布
        vo.setCtrDistribution(getCtrDistribution(advertiserId, startTime, endTime));

        return vo;
    }

    private MetricsDTO getMetrics(Long advertiserId, Date start, Date end) {
        return adScheduleMapper.selectMetrics(advertiserId, start, end);
    }

    private TrendDTO getTrendData(Long advertiserId, Date start, Date end) {
        List<DailyStatDTO> dailyStats = adScheduleMapper.selectTrend(advertiserId, start, end);

        TrendDTO trend = new TrendDTO();
        List<String> dates = new ArrayList<>();
        List<Long> impressions = new ArrayList<>();
        List<Long> clicks = new ArrayList<>();

        for (DailyStatDTO stat : dailyStats) {
            dates.add(stat.getDate());
            impressions.add(stat.getImpressions());
            clicks.add(stat.getClicks());
        }

        trend.setDates(dates);
        trend.setImpressions(impressions);
        trend.setClicks(clicks);

        return trend;
    }
    private List<TopAdDTO> getTopAds(Long advertiserId, Date start, Date end) {
        return adScheduleMapper.selectTopAds(advertiserId, start, end);
    }
    private List<CtrDistributionDTO> getCtrDistribution(Long advertiserId, Date start, Date end) {
        return adScheduleMapper.selectCtrDistribution(advertiserId, start, end);
    }
}
